package cn.demo.common.core.domain.model;

import cn.demo.common.core.domain.entity.SysDept;
import cn.demo.common.core.domain.entity.SysRole;
import cn.demo.common.core.domain.entity.SysUser;
import cn.demo.common.utils.CollectionUtils;
import cn.demo.common.utils.bean.BeanUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;

import java.io.Serializable;
import java.util.Collection;
import java.util.Set;

import static cn.demo.common.constant.CommonConstants.ADMIN_ID;

/**
 * 登录用户身份权限
 *
 * @author ruoyi
 */
@Data
public class LoginUser implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 用户ID
     */
    private String userId;

    /**
     * 部门ID
     */
    private String deptId;

    /**
     * 用户唯一标识
     */
    private String token;

    /**
     * 登录时间
     */
    private Long loginTime;

    /**
     * 过期时间
     */
    private Long expireTime;

    /**
     * 登录IP地址
     */
    private String ipaddr;

    /**
     * 登录地点
     */
    private String loginLocation;

    /**
     * 浏览器类型
     */
    private String browser;

    /**
     * 操作系统
     */
    private String os;

    /**
     * 权限列表
     */
    private Set<String> permissions;

    /**
     * 角色列表
     */
    private Set<String> roleKeys;
    private Set<SysRole> roles;

    /**
     * 部门权限列表
     */
    private Set<String> deptIds;

    /**
     * 用户信息
     */
    private UserInfo userInfo;
    /**
     * 用户信息
     */
    private SysDept deptInfo;

    public LoginUser() {

    }

    public LoginUser(SysUser sysUser) {
        this.userInfo = BeanUtils.copy(sysUser, UserInfo.class);
        this.userId = sysUser.getUserId();
        this.deptId = sysUser.getDeptId();
        this.deptInfo = sysUser.getDept();
    }

    public void syncBy(LoginUser user) {
        this.userInfo = user.getUserInfo();
        this.userId = user.getUserId();
        this.deptId = user.getDeptId();
        this.deptInfo = user.getDeptInfo();
        this.deptIds = user.getDeptIds();
        this.roleKeys = user.getRoleKeys();
        this.roles = user.getRoles();
        this.permissions = user.getPermissions();
    }

    @JsonIgnore
    public String getPassword() {
        return userInfo.getPassword();
    }

    public String getUsername() {
        return userInfo.getUserName();
    }

    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @JsonIgnore
    public boolean isAdmin() {
        if (ADMIN_ID.equals(userId)){
            return true;
        }else {
             return CollectionUtils.isNotEmpty(roleKeys) && roleKeys.contains("admin");
        }

    }
}
